{% extends "../base.html" %}
{% load admin_utils %}

{% block main_content %}
<div id="app-memberships-wrapper">
    <h3>应用成员列表</h3>
    <bk-button :theme="'primary'" :title="'新增成员'" class="mr10" @click="handleCreate">新增成员</bk-button>
    <bk-table style="margin-top: 15px;"
        :data="memberships">
        <bk-table-column type="index" label="序列" align="center" width="60"></bk-table-column>
        <bk-table-column label="成员姓名" prop="user.username" width="120"></bk-table-column>
        <bk-table-column label="角色" width="300">
            <template slot-scope="props">
                <div v-for="role in props.row.roles" class="permission-label">
                    <span>$[ roleIdToRole(role.id) ]</span>
                </div>
            </template>
        </bk-table-column>
        <bk-table-column label="权限" width="450">
            <template slot-scope="props">
                <div v-for="permission in PERMISSION_LIST" class="permission-label"
                :class="hasPerm(props.row.roles, permission) ? 'ok' : 'fail'">
                    <span>$[ permission ]</span>
                </div>
            </template>
        </bk-table-column>
        <bk-table-column label="操作">
            <template slot-scope="props">
                <bk-button theme="primary" text :disabled="props.row.status === '创建中'" @click="handleEdit(props.row.user)">更换角色</bk-button>
                <bk-button theme="primary" text @click="handleDelete(props.row.user)">删除成员</bk-button>
            </template>
        </bk-table-column>
    </bk-table>

    <bk-dialog v-model="dialogVisible" width="720"
        theme="primary"
        :mask-close="false"
        :loading="false"
        :title="form.type === 'create'? '新增成员' : '更换角色' "
        :confirm-fn="updateOrCreate">
        <div style="min-height: 130px;">
            <bk-form :model="form" :label-width="120" form-type="vertical">
                    <bk-form-item label="成员名称" :required="true">
                        <template v-if="form.type === 'create'">
                            <user-selector v-model="form.usernameList"></user-selector>
                        </template>
                        <template v-else>
                            <bk-input :readonly="true" v-model="form.username"></bk-input>
                        </template>
                    </bk-form-item>
                    <bk-form-item label="角色">
                        <bk-radio-group v-model="form.roleId">
                            <bk-radio class="mr20" :value="value" v-for="(value, chineseName) in ROLE_CHOICES">$[chineseName]</bk-radio>
                        </bk-radio-group>
                    </bk-form-item>
                    <bk-form-item label="权限列表">
                        <div v-for="permission in PERMISSION_LIST" class="permission-label"
                        :class="ROLE_PERMISSION_SPEC[form.roleId].indexOf(permission) !== -1 ?'ok' : 'fail'"
                        >
                            <span>$[ permission ]</span>
                        </div>
                    </bk-form-item>
                </bk-form>
        </div>
    </bk-dialog>
</div>
{% endblock %}

{% block main_script %}
<script>
    const application = {{ application | to_json }}

    const ROLE_CHOICES = {{ ROLE_CHOICES | to_json }}

    const ROLE_PERMISSION_SPEC = {{ ROLE_PERMISSION_SPEC | to_json }}

    const PERMISSION_LIST = {{PERMISSION_LIST | to_json }}

    const roleIdToRole = function (id) {
        for(key of Object.keys(ROLE_CHOICES)){
            if(ROLE_CHOICES[key] === id){
                return key
            }
        }
        return undefined
    }

    const hasPerm = function (roles, permission) {
        for (role of roles) {
            if (ROLE_PERMISSION_SPEC[role.id].indexOf(permission) !== -1) {
                return true
            }
        }
        return false
    }

    const URLRouter = {
        list: decodeURI("{% url 'admin.applications.detail.base_info.members.api' application.code %}"),
        detail: decodeURI("{% url 'admin.applications.detail.base_info.members.api' application.code %}"),
        delete: decodeURI("{% url 'admin.applications.detail.base_info.members.api' application.code '${username}' %}"),
    }

    document.addEventListener('DOMContentLoaded', () => {
        new Vue({
            el: "#app-memberships-wrapper",
            delimiters: ['$[', ']'],
            data: function () {
                return {
                    application,
                    loading: false,
                    loaded: false,
                    dialogVisible:false,
                    form: {
                        username: undefined,
                        usernameList: [],
                        type: 'create',
                        roleId: 2,
                    },
                    role: 2,
                    memberships: [],
                    ROLE_CHOICES,
                    ROLE_PERMISSION_SPEC,
                    PERMISSION_LIST
                }
            },
            mounted: function () {
                this.fetchAppMemberShips()
            },
            methods: {
                fetchAppMemberShips: function () {
                    if (this.loading) {
                        // 報錯
                        return
                    }
                    this.loading = true
                    this.memberships = []
                    this.loaded = false
                    this.$http.get(URLRouter.list).then(resp => {
                        this.memberships = resp
                        this.loaded = true
                    }).finally(err => {
                        this.loading = false
                    })
                },
                handleDelete: function (user, role){
                    let url = URLRouter.delete.replace('${username}', user.username)
                    this.$http.delete(url)
                    .then(resp => {
                        this.memberships = this.memberships.filter(x => x.user !== user)
                    })
                },
                handleEdit: function (user) {
                    this.form.username = user.username
                    this.form.roleId = 3
                    this.form.type = 'update'

                    this.dialogVisible = true
                },
                handleCreate: function () {
                    this.form.username = []
                    this.form.roleId = 3
                    this.form.type = 'create'
                    
                    this.dialogVisible = true
                },
                updateOrCreate: function () {
                    if(this.form.type === 'create') {
                        Promise.all(
                            this.form.usernameList.map(username => {
                                return this.$http.post(URLRouter.detail,
                                    {
                                        username,
                                        role: this.form.roleId
                                    }
                                )
                            })
                        ).then(() => {
                                this.dialogVisible = false
                                this.fetchAppMemberShips()
                        })
                    } else {
                        this.$http.post(URLRouter.detail,
                            {
                                username: this.form.username,
                                role: this.form.roleId
                            }
                        ).then(() => {
                                this.dialogVisible = false
                                this.fetchAppMemberShips()
                        })
                    }
                },
                roleIdToRole
            }
        })
    })
</script>
<style scoped>
    .role-radio {
        display: inline-block;
        padding: 0px 10px;
        * {
            cursor: pointer;
        }
    }
    .permission-label {
        display: inline-block;
        background: #fafafa;
        color: #999;
        font-size: 12px;
        border: 1px solid #ccc;
        vertical-align: middle;
        box-sizing: border-box;
        overflow: hidden;
        border-radius: 2px;
        white-space: nowrap;
        padding: 0 8px;
        height: 21px;
        line-height: 19px;
        border-radius: 21px;
        padding: 0 14px;
        margin: 0px 10px;
    }
    .ok {
        background-color: #e1f3ff;
        border-color: #3c96ff;
        color: #3c96ff;
    }
    .fail {
        border-color: #ebf0f5;
        color: #c3cdd7;
    }
    .user-photo {
        margin: 5px 0;
        display: inline-block;
        width: 40px;
        height: 40px;
        border-radius: 50%;
        overflow: hidden;
        border: solid 1px #eaeaea;
        vertical-align: middle;

        img {
            width: 100%;
            height: 100%;
        }
    }

    .user-name {
        display: inline-block;
        padding-left: 10px;
        font-size: 14px;
        color: #333;
        vertical-align: middle;
    }
</style>
{% endblock %}
